/*
 * Copyright (c) zhg2yqq.com Corp.
 * All Rights Reserved.
 */
package com.zhg2yqq.wheels.security.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;

import com.alibaba.fastjson2.JSON;
import com.zhg2yqq.wheels.common.dto.CurrentUserDTO;
import com.zhg2yqq.wheels.common.response.RestResponse;
import com.zhg2yqq.wheels.common.util.ServletUtils;
import com.zhg2yqq.wheels.security.CustomeSecurityProperties;
import com.zhg2yqq.wheels.security.ISecurityEventHook;
import com.zhg2yqq.wheels.security.ISecurityRepository;
import com.zhg2yqq.wheels.security.context.SecurityUserHolder;

/**
 * @author zhg2yqq, 2022年11月28日
 * @version zhg2yqq v1.0
 */
public class LogoutSuccessHandler
        implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {
    private Logger log = LoggerFactory.getLogger(LogoutSuccessHandler.class);
    private ISecurityEventHook eventHook;
    private ISecurityRepository securityRepository;
    private CustomeSecurityProperties securityProperties;

    public LogoutSuccessHandler(CustomeSecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    public LogoutSuccessHandler(CustomeSecurityProperties securityProperties,
                                ISecurityRepository securityRepository, ISecurityEventHook eventHook) {
        this.securityProperties = securityProperties;
        this.securityRepository = securityRepository;
        this.eventHook = eventHook;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication)
            throws IOException {
        if (eventHook != null) {
            CurrentUserDTO user = SecurityUserHolder.getUser();
            eventHook.logoutSuccessEvent(user, request);
        }
        if (securityRepository != null) {
            securityRepository.clearLoginUser(request);
        }
        if (ServletUtils.isAjaxRequest(request)) {
            // 允许跨域
            response.setHeader("Access-Control-Allow-Origin", "*");
            // 允许自定义请求头token(允许head跨域)
            response.setHeader("Access-Control-Allow-Headers",
                    "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(RestResponse.success()));
        } else if (securityProperties.getLogoutAfterUrl() != null) {
            response.sendRedirect(securityProperties.getLogoutAfterUrl());
        }
    }
}
